package client;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import entity.LogRec;
import exceptions.ReadDataException;

public class DataReader {
	private String logFileName;
	private String loginsFileName;
	
	public DataReader() {
	}
	
	public DataReader(String logFileName, String loginsFileName) {
		this.logFileName =logFileName;
		this.loginsFileName=loginsFileName;
	}

	private List<LogRec> readLogs() throws ReadDataException{
		List<LogRec> list = new ArrayList<LogRec>();
		
		File logs = new File(logFileName);
		try {
			FileInputStream fin = new FileInputStream(logs);
			DataInputStream in = new DataInputStream(fin);
			
			long count = logs.length()/372;
			for (int i = 0; i < count; i++) {
				LogRec log= new LogRec();
				
				byte[] username= new byte[32];
				in.read(username);
				String username1= new String(username).trim();
				log.setLogName(username1);
				in.skip(36);
				
				int id=in.readInt();
				log.setPid(id);
				
				short logType = in.readShort();
				log.setLogType(logType);
				in.skip(6);
				
				long time=in.readInt();
				log.setLogTime(time);
				in.skip(30);
				
				byte[] logIP = new byte[257];
				in.read(logIP);
				String ip=new String(logIP).trim();
				log.setLogIP(ip);
				in.skip(1);
				
				list.add(log);
			}
			
			fin.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new ReadDataException(e);
		}
		return list;
	}

	private List<LogRec> readLogins()throws ReadDataException{
		List<LogRec> list = new ArrayList<LogRec>();
		File f = new File(loginsFileName);
		if(!f.exists()||f.length()==0)
			return list;
		try {
			FileInputStream fin =new FileInputStream(loginsFileName);
			ObjectInputStream in = new ObjectInputStream(fin);
			list=(List<LogRec>) in.readObject();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new ReadDataException(e);
		}
		
		return list;
	}
	
	public List<LogRec> getAllLogs()throws ReadDataException{
		List<LogRec> list1=readLogins();
		List<LogRec> list2=readLogs();
		list1.addAll(list2);
		return list1;
	}
	
}
